﻿#include "DialogPythonScriptEditing.h"
#include "ui_DialogPythonScriptEditing.h"

#include <QTabWidget>
#include <QFileDialog>
#include <QPushButton>
#include <QTextStream>
#include <QMessageBox>
#include <QTabBar>
#include <QIntValidator>
#include "IdaWidgetHelper.h"
#include "BaseWidget/IdaDialogMsg.h"
#include "DataImportConfigurationData.h"

namespace pst
{
    DialogPythonScriptEditing::DialogPythonScriptEditing(QWidget* parent)
        : IdaDialogFrame(parent)
        , ui(new Ui::DialogPythonScriptEditing())
    {
        ui->setupUi(this);
        setWindowTitle(QStringLiteral("编辑脚本"));
        ui->pushButton_save->setStyleSheet("QPushButton {"
            "border: 1px solid #3D6D99;"
            "color: #FFFFFF;"
            "background-color: #3D6D99;"
            "}");

        connect(ui->pushButton_save, &QPushButton::clicked, this, &DialogPythonScriptEditing::accept);
        connect(ui->pushButton_cancel, &QPushButton::clicked, this, &DialogPythonScriptEditing::reject);
    }

    DialogPythonScriptEditing::~DialogPythonScriptEditing()
    {
        delete ui;
    }

    void DialogPythonScriptEditing::initPythonContent()
    {
        ui->label_Name->setText(m_PythonScriptFilePath);
        if (!m_PythonScriptFilePath.isEmpty())
        {
            QFile file(m_PythonScriptFilePath);   //不为空，创建文件对象
            if (!file.open(QFile::ReadOnly | QFile::Text))
            {
                //无法读取文件提示
                auto _res = IdaDialogMsg::showDialog(nullptr, QStringLiteral("打开文件失败！"), EDialogMsg::Warning, QStringLiteral("警告"), { QStringLiteral("确定") });
            }
            else
            {
                QByteArray data = file.readAll();
                QString text = QString::fromUtf8(data);
                ui->textEdit_content->setText(text);
            }
        }
    }

    void DialogPythonScriptEditing::setPythonScriptFilePath(const QString& filePath)
    {
        m_PythonScriptFilePath = filePath;
        initPythonContent();
    }

    void DialogPythonScriptEditing::reject()
    {

        IdaDialogFrame::reject();
    }

    void DialogPythonScriptEditing::accept()
    {
        QFile file(m_PythonScriptFilePath);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream out(&file); //IO设备对象的地址对其进行初始化
            out.setCodec("UTF-8");

            out << ui->textEdit_content->toPlainText() << endl; //输出

            //QMessageBox::warning(this, tr("Finish"), tr("Successfully save the file!"));

            file.close();

            emit sendNewText(m_PythonScriptFilePath, ui->textEdit_content->toPlainText().trimmed());
        }
        else
        {
            auto _res = IdaDialogMsg::showDialog(nullptr, QStringLiteral("保存文件失败！"), EDialogMsg::Warning, QStringLiteral("警告"), { QStringLiteral("确定") });
        }
        IdaDialogFrame::accept();
    }


}
